package ymodels

import (
	"fmt"
	"io/ioutil"

	yaml "gopkg.in/yaml.v2"
)

type pGConfig struct {
	HostName    string `yaml:"HostName"`
	Port        int    `yaml:"Port"`
	User        string `yaml:"User"`
	Password    string `yaml:"Password"`
	Dbname      string `yaml:"Dbname"`
	SSLMode     string `yaml:"SSLMode"`
	SSLCert     string `yaml:"SSLCert"`
	SSLKey      string `yaml:"SSLKey"`
	SSLRootCert string `yaml:"SSLRootCert"`
}

// GetPGConfig 获取数据库配置
func GetPGConfig(path string) (string, error) {
	dbuf, err := ioutil.ReadFile(path)
	if err != nil {
		return "", err
	}
	conf := pGConfig{}
	err = yaml.Unmarshal(dbuf, &conf)
	if err != nil {
		return "", err
	}
	var pgDS string
	if conf.SSLMode == "require" {
		pgDS = fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=require sslcert=%s sslkey=%s sslrootcert=%s",
			conf.HostName,
			conf.Port,
			conf.User,
			conf.Password,
			conf.Dbname,
			conf.SSLCert,
			conf.SSLKey,
			conf.SSLRootCert,
		)
	} else {
		pgDS = fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable",
			conf.HostName,
			conf.Port,
			conf.User,
			conf.Password,
			conf.Dbname,
		)
	}
	return pgDS, nil
}
